<template>
  <div class="table1">
    <div class="btn-wrap">
      <a-button type="primary" style="margin-right: 15px;" @click="onAdd">添加</a-button>
      <a-button type="info" @click="download">导出</a-button>
    </div>
    <z-table ref="table" rowKey="id" :showAlert="false" :showSelection="true" :loading="loading" :columns="columns"
      :dataSource="pageData" @selectedRow="onSelectedRow" @change="onTableChange">
      <!--操作-->
      <template slot="action" slot-scope="text, record">
        <a-button @click="onDetail(record)" type="link" style="padding:0;">查看</a-button>
      </template>
      <template slot="status" slot-scope="text, record">
        <span v-if="text == 1" style="color: red">未提交</span>
        <span v-if="text == 2" style="color: green">已提交</span>
      </template>
    </z-table>
    <a-modal width="920px" title="添加" :visible="addFormVisible" @ok="onAddSubmit" @cancel="onAddFormCancel">
      <a-form-model ref="addForm" :model="addForm" :label-col="{span: 6}" :wrapper-col="{span: 18}">
        <a-form-model-item label="社工名称">
          <a-input v-model="unitOwnerName" disabled />
        </a-form-model-item>
        <a-form-model-item label="单元名称" props="unitId"  :rules="{required: true, message: '请输入社工总结', trigger: ['blur']}">
          <a-select v-model="addForm.unitId"  @change="onUnitChange">
            <a-select-option :value="item.id" v-for="item in unitList" :item="item" :key="id">第{{item.unitOrder + 1}}单元</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="本单元（节）主题">
          <a-input v-model="unitMainContent" disabled />
        </a-form-model-item>
        <a-form-model-item label="负责社工">
          <a-input v-model="unitOwnerName" disabled />
        </a-form-model-item>
        <a-form-model-item label="活动地点">
          <a-input v-model="location" disabled />
        </a-form-model-item>
        <!-- <a-table :columns="formColumns" :data-source="addForm.satisfactionData" row-key="id" :pagination="false">
            <template slot-scope="text, record, index" slot="level">
              <a-select v-model="addForm.satisfactionData[index].itemLevel">
                <a-select-option :value="1">A</a-select-option>
                <a-select-option :value="2">B</a-select-option>
                <a-select-option :value="3">C</a-select-option>
                <a-select-option :value="4">D</a-select-option>
              </a-select>
            </template>
          </a-table> -->
        <a-row>
          <a-col :span="6">
            <div class="required">自评表：</div>
          </a-col>
          <a-col :span="18">
            <table class="form-table" style="width: 100%" border="1">
              <thead>
                <tr>
                  <th>基本指标</th>
                  <th>内容</th>
                  <th>满分</th>
                  <th>得分</th>
                </tr>
              </thead>
              <tbody>
                <!-- <template v-for="(item, index) in metrics" >
                  <tr :key="index">
                    <td :colspan="item.metrics.length">{{item.groupName}}</td>
                    <td v-for="(child, count) in item.metrics" :key="count">{{child.metricName}}</td>
                  </tr>
                </template> -->
                <template v-for="(item, index) in addForm.records">
                  <tr :key="index + '-first'">
                    
                    <td  :rowspan="item.metrics.length">{{item.groupName}}</td>
                    <td>{{item.metrics[0].metricName}}</td>
                    <td>{{item.metrics[0].metricScore}}</td>
                    <td>
                      <a-form-model-item :prop="`records.${index}.metrics.0.selfEvaluationScore`" :rules="{required: true, message: '请输入分数', trigger: ['blur']}">
                        
                        <a-input-number style="width: 100%;margin-top: 25px;" v-model="addForm.records[index].metrics[0].selfEvaluationScore" :min="1" :max="item.metrics[0].metricScore"/>
                      </a-form-model-item>
                    </td>
                  </tr>
                  <tr v-for="(child, count) in item.metrics" :key="index + '-' + count + '-child'" v-if="count > 0">
                  
                    <td>{{child.metricName}}</td>
                    <td>{{child.metricScore}}</td>
                    <td>
                      
                      <a-form-model-item :prop="`records.${index}.metrics.${count}.selfEvaluationScore`" :rules="{required: true, message: '请输入分数', trigger: ['blur']}">
                        <a-input-number style="width: 100%;margin-top: 25px;" v-model="addForm.records[index].metrics[count].selfEvaluationScore" :min="1" :max="child.metricScore"/>
                      </a-form-model-item>
                    </td>
                  </tr>
                </template>
                
              </tbody>
            </table>
          </a-col>
        </a-row>
        <a-form-model-item label="社工总结" prop="summaryContent" :rules="{required: true, message: '请输入社工总结', trigger: ['blur']}">
          <a-input v-model="addForm.summaryContent" />
        </a-form-model-item>
        <a-form-model-item label="协助同事的建议">
          <a-input v-model="addForm.adviceContent" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
  import {
    memberList
  } from '@/api/sjsk/activity/group/detail/mature/table1'
  import {
    getList,
    add,
    update,
    detail,
    selfEvalMetrics
  } from '@/api/sjsk/activity/group/detail/end/table4'
  import { unitList } from '@/api/sjsk/activity/common'
  import downloadXlsl from '../../downloadXlsx.js'
  export default {
    props: {
      detail: Object
    },
    data() {
      return {
        loading: false,
        pageFilter: {
          pageNo: 1,
          pageSize: 10
        },
        pageData: {},
        form: {},
        headerData: [],
        memberList: [],
        selectKeys: [],
        
        unitList: [],
        addFormVisible: false,
        addForm: {
          "adviceContent": "",
            "activityId": 0,
            "summaryContent": "",
            "records": [],
            "unitId": '',
            "memberId": ''
        },
        
        location: '',
        unitOwnerName: '',
        unitMainContent: ''
        
      }
    },
    created() {
      this.addForm.activityId = this.$route.query.id
      this.getMemberList()
      this.onQuery()
      this.getUnitList()
      this.getSelfEvalMetrics()
      
    },
    computed: {
      columns: function() {
        let columns = [{
          title: '社工名称',
          dataIndex: 'unitOwnerName',
          width: 100,
          align: 'center'
        }]
        this.headerData.map((item, index) => {
          columns.push({
            title: `第${index + 1}单元`,
            dataIndex: item.relateKey,
            width: 100,
            align: 'center',
          scopedSlots: {
            customRender: 'status'
          }
          })
        })
        columns.push({
          title: '最新提交时间',
          dataIndex: 'lastUpdatedDate',
          width: 140,
          align: 'center'
        })
        columns.push({
          title: '操作',
          width: 120,
          align: 'center',
          dataIndex: 'action',
          scopedSlots: {
            customRender: 'action'
          }
        })
        return columns
      }
    },
    methods: {
      download() {
        downloadXlsl(this.$route.query.id, 11)
      },
      getUnitList() {
        unitList({
          activityId: this.$route.query.id
        }).then(res => {
          this.unitList = res.result
        })
      },
      onUnitChange(e, opt) {
        const { activityLocation, activityAddress, unitOwnerName, unitMainContent } = opt.data.attrs.item
        this.location = activityLocation + activityAddress
        this.unitOwnerName = unitOwnerName
        this.unitMainContent = unitMainContent
        console.log(e)
        console.log(opt)
      },
      getSelfEvalMetrics() {
        selfEvalMetrics({
          activityId: this.$route.query.id
        }).then(res => {
          const records = res.result.map(item => {
            item = item.metrics.map(child => {
              child.selfEvaluationScore = ''
              return child
            })
            return item
          })
          this.addForm.records = res.result
        })
      },
      onAdd() {
        console.log(this.detail)
        this.addFormVisible = true
        
      },
      getMemberList() {
        memberList({
          activityId: this.$route.query.id
        }).then(res => {
          if (res.success) {
            this.memberList = res.result.records
          }
        })
      },
      onQuery() {
        this.pageFilter.pageNo = 1
        this.refreshTable()
      },
      onSelectedRow(keys) {
        this.selectKeys = keys
        console.log(keys)
        this.isDisabled = keys.length > 0 ? false : true
      },
      onTableChange(pagination, pageFilter, sorter) {
        let keyMap = {
          currentPage: 'pageNo'
        }
        let paginations = Object.keys(pagination).reduce((newData, key) => {
          let newKey = keyMap[key] || key
          newData[newKey] = pagination[key]
          return newData
        }, {})
        this.pageFilter = Object.assign({}, this.pageFilter, paginations)
        this.refreshTable()
      },
      refreshTable() {
        let form = Object.assign({}, this.queryParam, this.pageFilter)
        form.activityId = this.$route.query.id
        this.loading = true
        getList(form).then((res) => {
            if (res.success) {
              res.result.data.records = res.result.data.records.map(item => {
                for (let key in item.selfEvalData) {
                  item[key] = item.selfEvalData[key]
                }
                return item
              })
              this.pageData = res.result.data
              this.headerData = res.result.unitTableHeaders
              this.loading = false
              this.$refs.table.onClearRowKeys()
            } else {
              this.loading = false
            }
          })
          .catch((e) => {
            this.loading = false
            this.$message.warn('请求失败！')
          })
      },
      onAddSubmit() {
        
        this.$refs.addForm.validate().then(() => {
          const form = JSON.parse(JSON.stringify(this.addForm))
          let records = []
          form.records.map(item => {
            item.metrics.map(child => {
              child.metricId = child.id
              delete child.id
              records.push(child)
            })
          })
          form.records= records
          add(form).then(res => {
            this.$message.success('添加成功！')
            this.addFormVisible = false
            this.onQuery()
          })
        }).catch(() => {
          this.$message.warning('请完整填写表单后，再进行提交！')
        })
      },
      onAddFormCancel() {
        this.addFormVisible = false
        this.addForm = {
          "adviceContent": "",
            "activityId": 0,
            "summaryContent": "",
            "records": [],
            "unitId": '',
            "memberId": ''
        }
        this.getSelfEvalMetrics()
      }
    }
  }
</script>

<style lang="less" scoped>
  .table1 {
    box-sizing: border-box;
    padding: 20px 30px;
    
    .btn-wrap {
      margin-bottom: 20px;
    }
  }
  .required {
    text-align: right;
  
    &::before {
      content: '*';
      color: red;
      margin-right: 5px;
    }
  
  }
  .form-table{
    margin-bottom: 15px;
    border-color: #eee;
    th{
      height: 53px;
      background-color: #f5f5f5;
      
    }
    th,td {
      padding-left: 8px;
    }
  }
</style>
